package org.example.service.impl;

import cn.hutool.http.HttpStatus;
import org.example.entity.*;
import org.example.service.UserService;
import org.example.mapper.UserMapper;
import org.example.utils.JwtUtil;
import org.example.utils.RedisCache;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

/**
* @author hasee
* &#064;description  针对表【User】的数据库操作Service实现
* &#064;createDate  2022-09-07 09:34:14
 */
@Service
public class UserServiceImpl implements UserService{

    @Resource
    private UserMapper userMapper;
    @Resource
    private PasswordEncoder encoder;
    @Resource
    private RedisCache redisCache;
    @Value("${login.tokenExpireTime}")
    private int tokenExpireTime;
    @Resource
    private AuthenticationManager authenticationManager;
    @Override
    public CommonResult<Integer> register(User user) {
        user.setPassword(encoder.encode(user.getPassword()));
        int insert = userMapper.insert(user);
        return insert > 0 ? new CommonResult<>(HttpStatus.HTTP_OK, "注册成功", insert) : new CommonResult<>(HttpStatus.HTTP_INTERNAL_ERROR, "注册失败", null);
    }

    @Override
    public CommonResult<Integer> updateUser(User user) {
        int i = userMapper.updateById(user);
        return i>0?new CommonResult<>(HttpStatus.HTTP_OK,"修改成功",i):new CommonResult<>(HttpStatus.HTTP_INTERNAL_ERROR,"修改失败",null);
    }

    @Override
    public CommonResult<Object> login(LoginInfo loginInfo) {
        UsernamePasswordAuthenticationToken token=
                new UsernamePasswordAuthenticationToken(loginInfo.getUsername(),loginInfo.getPassword());
        Authentication authenticate = this.authenticationManager.authenticate(token);
        if (!authenticate.isAuthenticated()){
            return new CommonResult<>(HttpStatus.HTTP_UNAUTHORIZED,"用户名或密码错误",null);
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        return this.loginSuccess(loginUser);
    }

    @Override
    public CommonResult<String> logout() {
        try {
            UsernamePasswordAuthenticationToken token=
                    (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
            LoginUser loginUser = (LoginUser) token.getPrincipal();
            String username = loginUser.getUsername();
            this.redisCache.deleteObject("work:"+username);
            return new CommonResult<>(HttpStatus.HTTP_OK,"注销成功",null);
        }catch (Exception e){
            return new CommonResult<>(HttpStatus.HTTP_INTERNAL_ERROR,"注销失败",null);
        }
    }

    private CommonResult<Object> loginSuccess(LoginUser loginUser) {
        String username = loginUser.getUsername();
        String jwt = JwtUtil.createJWT(username);
        //把token存入redis中，并设置过期时间为tokenExpireTime（默认8天）
        this.redisCache.setCacheObject("work:" + username, loginUser, this.tokenExpireTime, TimeUnit.DAYS);
        CommonUserInfo commonUserInfo = loginUser.getCommonUserInfo();
        commonUserInfo.setToken(jwt);
        return new CommonResult<>(HttpStatus.HTTP_OK, "登录成功", commonUserInfo);
    }
}




